<template>
  <div>
    <!-- <el-dropdown
      v-if="isPublishedType && !selection.find(v => v.allowShare)"
      @command="command => inlineShare(command)">
      <el-button
        v-if="isPublishedType"
        :disabled="!selection.length"
        type="plain-third">
        <i class="iconfont icon-share1"></i>批量分享
      </el-button>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item command="dept">部门</el-dropdown-item>
        <el-dropdown-item command="person">人员</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown> -->
    <!-- <el-button
      v-if="isPublishedType"
      type="plain-third"
      :disabled="!selection.length"
      @click="shareDocument()">
      <i class="iconfont icon-share1"></i>批量分享
    </el-button> -->
    <base-modal :title="$t('common.base.share')" class="type-modal" width="500px" :show.sync="shareBoxShow">
      <div class="wiki-share-wrap">
        <p>{{$t('wiki.component.documentShare.des1')}}</p>
        <el-radio-group class="pad-b-18" v-model="shareType">
          <el-radio :label="0">{{$t('wiki.component.documentShare.btn1')}}</el-radio>
          <el-radio :label="1">{{$t('wiki.component.documentShare.btn2')}}</el-radio>
          <el-radio :label="2" v-show="outsideShow">{{$t('wiki.component.documentShare.btn3')}}</el-radio>
        </el-radio-group>
        <div class="external-share" v-show="shareType == 2 && shareUrls.length">
          <div class="external-share-item" @click="outlineShare">
            <p>{{$t('wiki.component.documentShare.externalShareTitle1')}} <i class="iconfont icon-fd-link"></i></p>
          </div>
          <div class="external-share-item" @click="downloadQrcode" v-if="shareUrls.length == 1">
            <div class="share-modal" id="qrcode" ref="qrcode"></div>
            <p>{{$t('wiki.component.documentShare.externalShareTitle2')}} <i class="iconfont icon-erweima"></i></p>
          </div>
        </div>
      </div>

      <div slot="footer" class="edit-footer">
        <!-- <el-dropdown @command="command => inlineShare(command)">
          <el-button>对内分享</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="dept">部门</el-dropdown-item>
            <el-dropdown-item command="person">人员</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown> -->
        <el-button @click="shareBoxShow = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" :loading="shareLoading" @click="confirm">{{$t('common.base.confirm')}}</el-button>
        <!-- <el-button @click="inlineShare('dept')">{{$t('wiki.component.documentShare.btn1')}}</el-button>
        <el-button @click="inlineShare()">{{$t('wiki.component.documentShare.btn2')}}</el-button>
        <el-button
          :loading="shareLoading"
          type="primary"
          class="green-btn"
          @click="getShareUrl()"
          v-if="wikiList.find(v => v.allowShare)">{{$t('wiki.component.documentShare.btn3')}}</el-button> -->
      </div>
    </base-modal>
  </div>
</template>

<script>

import { getShareLink, shareDocument } from '@src/api/Repository';
import Clipboard from 'clipboard';

import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'

import { debounce } from 'lodash'
import QRCode from 'qrcodejs2'

export default {
  name: 'document-share',
  props: {
    // bodyType: {
    //   type: String,
    //   default: 'icon'
    // },
    wikiList: {
      type: Array
    }
  },
  data() {
    return {
      shareBoxShow: false,
      shareUrls: [],
      // wikiList: [],
      shareInfo: {
        selectedUsers: [],
        selectedDepts: [],
      },
      shareLoading: false,
      shareType:0,
      outsideShow: true, //是否显示外部分享按钮
    }
  },
  watch: {
    async shareType(value) {
     if(value == 2) {
      await this.getShareUrl();
      if(this.shareUrls.length == 1) {
        this.createQrcode();
      }
     }
    }
  },
  methods: {
    /* 下载二维码 */
    downloadQrcode() {
      let qrcode = document.getElementById('qrcode');
      let canvas = qrcode.getElementsByTagName('canvas');

      // 创建a标签，将canvas变成png图片
      let a = document.createElement('a');
      a.href = canvas[0].toDataURL('image/png');
      // 设置下载文件的名字
      a.download = this.$t('wiki.component.documentShare.externalShareTitle3');

      a.click();
    },
    /* 生成二维码 */
    createQrcode() {
      const shareUrls = this.shareUrls[0] || '';

      // 清除已经生成的二维码
      this.$refs.qrcode.innerHTML = '';

      // 生成二维码
      new QRCode('qrcode', {
        width: 132,
        height: 132,
        text: shareUrls
      });

    },
    // 分享
    shareDocument(showEnable) {
      // 批量分享或分享功能都是外部分享才显示外部分享按钮
      this.outsideShow = showEnable
      this.shareBoxShow = true;
      this.shareType = 0;
      // if (this.wikiList.find(v => v.allowShare)) {
      //   this.getShareUrl();
      // }
      //  else {
      //   this.inlineShare();
      // }
    },
    // 内部分享，选择人员或者组织
    inlineShare(type = 'person') {
      this.shareBoxShow = false;
      type === 'dept' ? this.selectTeam() : this.choosePerson();
    },

    // 外部分享，将连接添加至剪切板
    outlineShare() {
      // 外部文章选择外部分享时
      let _this = this;
      let url = this.shareUrls.join('\n');

      // 获取body
      let body = document.getElementsByTagName("body")[0];

      let copyFrom = document.createElement("a");
      copyFrom.setAttribute("id", "target");
      copyFrom.setAttribute("target", "_blank");
      copyFrom.setAttribute("href", url);
      copyFrom.innerHTML = url;

      // 创建按钮
      let agent = document.createElement("button");
      // body增加超链接
      body.appendChild(copyFrom);
      // body增加按钮
      body.appendChild(agent); // 采用Clipboard.js方案 // trouble：没有可以传入的HTML元素，但我们可以动态创建一个DOM对象作为代理，复制超链接

      let clipboard = new Clipboard(agent, {
        target() {
          return document.getElementById('target');
        }
      });

      clipboard.on('success', function(e) {
        _this.$platform.notification({
          title: _this.$t('wiki.component.documentShare.tips1'),
          type: 'success',
        });
      });

      clipboard.on('error', function(e) {
        _this.$platform.notification({
          title: _this.$t('wiki.component.documentShare.tips2'),
          type: 'error',
        });
      });
      // 点击按钮
      agent.click();
      // 移除创建的元素
      body.removeChild(copyFrom);
      body.removeChild(agent);
    },

    async getShareUrl() {
      this.shareUrls = []
      try {
        let protocol = window.location.protocol;
        let host = window.location.host;
        let originalUrls = []
        this.wikiList.filter(v => v.allowShare).forEach(v => {
          originalUrls.push(`${protocol}//${host}/v_open/wiki/view?wikiId=${v.id}`)
        })
        this.shareUrls = await getShareLink({
          originalUrls
        });
        // this.outlineShare()
      } catch (error) {
        console.error("error", error);
      }
    },

    /** 选择团队  */
    selectTeam() {
      let options = {
        max: -1,
        mode: BaseSelectUserModeEnum.Filter,
        isCanChooseRole: false,
      };
      
      this.$fast.select.multi.all(options).then(res => {
        if (res.status === 0) {
          let data = res.data || {}
          let users = data.users || []
          let depts = data.depts || []
          let serviceProviders = data.serviceProviders || []

          this.shareInfo.selectedUsers = users
          this.shareInfo.selectedDepts = depts.concat(serviceProviders)
          // this.$el.dispatchEvent(
          //   new CustomEvent("form.validate", { bubbles: true })
          // );
          this.submitShare()
        }
      }).catch(err => console.error(err))
    },

    // 点击加号显示标签输入框
    choosePerson() {
      let max = -1;

      let options = {
        title: this.$t('wiki.component.documentShare.title1'),
        seeAllOrg: true,
        max,
        mode:BaseSelectUserModeEnum.Filter
      };
      
      return this.$fast.select.multi.user(options)
        .then((result) => {
          if (result.status == 0) {
            let data = result.data || {};
            let users = data.users || [];

            this.shareInfo.selectedUsers = users;
            // this.$el.dispatchEvent(
            //   new CustomEvent("form.validate", { bubbles: true })
            // );
            this.submitShare();
          }
        })
        .catch((err) => console.error(err));
    },

    // 内部分享选择人员确定后
    async submitShare() {
      if (!this.shareInfo.selectedUsers || !this.shareInfo.selectedDepts) return;

      try {
        let userIds = this.shareInfo.selectedUsers.map((item) => item.userId);
        let tagIds = this.shareInfo.selectedDepts.map((item) => item.id)
        let params = {
          wikiIds: this.wikiList.map(v => v.id),
          userIds,
          tagIds
        }

        let res = await shareDocument(params);

        if (res.success) {
          this.$platform.notification({
            title: this.$t('wiki.component.documentShare.title2'),
            type: "success",
          });
        } else {
          this.$platform.notification({
            title: res.message,
            type: "error",
          });
        }
      } catch (err) {
        console.error(err);
      }
    },
    confirm:debounce(function(){
      if(this.shareType == 0){
        this.inlineShare('dept')
      }else if(this.shareType == 1){
        this.inlineShare()
      }else {
        this.shareBoxShow = false;
        // this.getShareUrl()
      }
    }, 100)
  }
}
</script>

<style lang="scss" scoped>
  ::v-deep .type-modal {

    .base-modal-body {
      .wiki-share-wrap {
        height: 100px;
      }
    }

    .base-modal-footer {
      text-align: right;
    }

    .el-button:hover, .el-button:focus {
      color:  $color-primary-light-5;
      border-color: #cce9e9;
      background-color: $color-primary-light-1;
    }

    .el-button--primary:hover, .el-button--primary:focus {
      background: #77c5c3;
      border-color: #77c5c3;
      color: #FFFFFF;
    }

    .green-btn {
      background: $color-primary-light-5;
      border: transparent;
    }
    .external-share {
      display: flex;
      justify-content: flex-start;
      .external-share-item {
        width: 166.5px;
        height: 32px;
        line-height: 32px;
        border-radius: 4px;
        background: #F5F5F5;
        text-align: center;
        cursor: pointer;
        #qrcode {
          display: none;
        }
        .iconfont {
          color: $color-primary;
        }
        &:first-child {
          margin-right: 12px;
        }
      }
    }
  }
</style>